package com.jy.modules.cims.settle.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.InteractException;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService;
import com.jy.modules.cims.component.credit.creditor.common.ISettlePlan;
import com.jy.modules.cims.component.creditRight.ICCreditRight;
import com.jy.modules.cims.component.deal.ICDeal;
import com.jy.modules.cims.component.sysAssist.AbstractDueExecuteTaskManager;
import com.jy.modules.cims.component.sysAssist.BatchService;
import com.jy.modules.cims.component.sysAssist.SettleDateImpl;
import com.jy.modules.cims.data.common.dao.TCMmCostPlanDao;
import com.jy.modules.cims.data.common.dao.TCMmCreditDealDetailDao;
import com.jy.modules.cims.data.common.dao.TCMmCreditDetailDao;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCostPlanDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDealDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.dao.CreditRedemptionDao;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.RedemptionCreditDetailDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateResultDto;
import com.jy.modules.cims.data.dto.credit.CreditValueChangedParam;
import com.jy.modules.cims.data.dto.credit.RedeemParamDto;
import com.jy.modules.cims.data.dto.credit.RedeemResultDto;
import com.jy.modules.cims.data.interact.core.credit.response.ResponseBackCreditValueDTO;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.interact.InteractClassInvokeService;
import com.jy.platform.core.common.BaseDTO;

/**
 * 赎回处理服务层
 */
@Service("com.jy.modules.cims.settle.service.CreditRedemptionService")
public class CreditRedemptionService {

	private static final Logger logger = LoggerFactory.getLogger(CreditRedemptionService.class);
	
	@Autowired
	public TCMmCreditDetailDao creditDetailDao;
	@Autowired
	public TCMmCreditDealDetailDao creditDealDetailDao;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.deal.CDealImpl")
	public ICDeal iCDeal;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.creditRight.CCreditRightImpl")
	private ICCreditRight creditRight;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
	private TCMmCooperorgDealService cooperorgDealService;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService")
	private TCMmCreditDealDetailService creditDealDetailService;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.BatchService")
	public BatchService batchService;
	/**
	 * 系统交互处理服务层
	 */
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.InteractClassInvokeService")
	private InteractClassInvokeService interactClassInvokeService;
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	private ICInteract iCInteract;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.DueExecuteTaskManager")
	public AbstractDueExecuteTaskManager abstractDueExecuteTaskManager;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.credit.creditor.common.SettlePlan")
	public ISettlePlan settlePlan;

	@Autowired
	public DealDao dealDao;
	
	@Autowired
	private TCMmCostPlanDao costPlanDao;
	
	@Autowired
	private CreditRedemptionDao creditRedemptionDao;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	private DealService dealService;
	

	/**
	 * 根据债权包查询债权明细
	 * 
	 * @Title getCreditDetailRedemptionList
	 * @Description TODO
	 * @param searchParams
	 * @return List<TCMmCreditDetailDTO>
	 * @author lizhiqiang
	 * @date 2015-3-3-下午2:36:46
	 * @update
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> getCreditDetailRedemptionList(Map<String, Object> searchParams) {
		return creditDetailDao.searchTCMmCreditDetailByPaging(searchParams);
	}
	
	/**
	 * 可赎回债权明细
	 * @Title getCreditDetailListByRedempDetail
	 * @Description TODO
	 * @param searchParams
	 * @return 
	 * List<CreditDetailDto> 
	 * @author lizhiqiang
	 * @date 2016-6-7-下午2:12:05
	 * @update 
	 * @throws
	 */
	public List<CreditDetailDto> getCreditDetailListByRedempDetail(Map<String, Object> searchParams) {
		return creditRedemptionDao.getCreditDetailListByPaging(searchParams);
	}
	/**
	 * 可赎回债权明细
	 * @Title getCreditDetailListByRedempDetail
	 * @Description TODO
	 * @param searchParams
	 * @return 
	 * List<CreditDetailDto> 
	 * @author lizhiqiang
	 * @date 2016-6-7-下午2:12:05
	 * @update 
	 * @throws
	 */
	public List<CreditDetailDto> getCreditDetailListByRedempDetailByExport(Map<String, Object> searchParams) {
		return creditRedemptionDao.getCreditDetailList(searchParams);
	}
	
	/**
	 * 根据债权包(包含月还二次购买债权包)查询债权明细【贷款回购】 分页
	 * 
	 * @Title getCreditDetailRedemptionLists
	 * @Description TODO
	 * @param searchParams
	 * @return List<TCMmCreditDetailDTO>
	 * @author yujiazheng
	 * @date 2015-3-3-下午2:36:46
	 * @update
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> getLoanRedemptionCreditDetailByPaging(Map<String, Object> searchParams) {
		return creditDetailDao.searchLoanRedemptionCreditDetailByPaging(searchParams);
	}
	/**
	 * 根据债权包(包含月还二次购买债权包)查询债权明细【贷款回购】 分页
	 * 
	 * @Title getCreditDetailRedemptionLists
	 * @Description TODO
	 * @param searchParams
	 * @return List<TCMmCreditDetailDTO>
	 * @author yujiazheng
	 * @date 2015-3-3-下午2:36:46
	 * @update
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> getLoanRedemptionCreditDetail(Map<String, Object> searchParams) {
		return creditDetailDao.searchLoanRedemptionCreditDetail(searchParams);
	}
	
	/**
	 * 选择赎回债权，转换指定日期的债权价值
	 * 
	 * @param creditDetailList
	 * @param redeemDate
	 * @return
	 */
	public List<TCMmCreditDetailDTO> getCreditDetailRedemptionListByInterface(List<TCMmCreditDetailDTO> creditDetailList, Date redeemDate) {

		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		iInteractAssist.registerDealIrtService(busiNoForInteract);

		CreditValueCalculateDto creditValueCalculateDto = new CreditValueCalculateDto();
		List<CreditValueCalculateDto.CreditValueCalculateBatch> batchIdList = new ArrayList<CreditValueCalculateDto.CreditValueCalculateBatch>();
		/* 保存执行上下文 */
		for (TCMmCreditDetailDTO creditDetail : creditDetailList) {
			CreditValueCalculateDto.CreditValueCalculateBatch cc = new CreditValueCalculateDto.CreditValueCalculateBatch();
			cc.setTransferId(creditDetail.getTransferId());
			cc.setCreidtId(creditDetail.getCreditCode());
			cc.setCreditDate(redeemDate);
			cc.setEachRepaymentValue(creditDetail.getThisRepaySum());
			batchIdList.add(cc);
		}
		creditValueCalculateDto.setBatchIdList(batchIdList);
		creditValueCalculateDto.setDealCode(busiNoForInteract);
		List<CreditValueCalculateResultDto> rslist = iCInteract.getCreditValue(creditValueCalculateDto);
		if (rslist == null) {
			return null;
		}
		Map<String, CreditValueCalculateResultDto> map = new HashMap<String, CreditValueCalculateResultDto>();
		for (CreditValueCalculateResultDto creditValueCalculateResultDto : rslist) {
			map.put(creditValueCalculateResultDto.getTransferId(), creditValueCalculateResultDto);
		}
		List<TCMmCreditDetailDTO> resultlist = new ArrayList<TCMmCreditDetailDTO>();
		for (TCMmCreditDetailDTO tcMmCreditDetailDTO : creditDetailList) {
			CreditValueCalculateResultDto creditValueCalculateResultDto = map.get(tcMmCreditDetailDTO.getTransferId());
			tcMmCreditDetailDTO.setThisMakeCreditorValue(creditValueCalculateResultDto.getCreditValue());
			resultlist.add(tcMmCreditDetailDTO);
		}

		return resultlist;
	}
	
	/**
	 * 选择赎回债权，转换指定日期的债权价值
	 * 
	 * @param creditDetailList
	 * @param redeemDate
	 * @return
	 */
	public List<CreditDetailDto> getCreditDetailRedemptionList(List<CreditDetailDto> creditDetailList, Date redeemDate) {

		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		iInteractAssist.registerDealIrtService(busiNoForInteract);

		CreditValueCalculateDto creditValueCalculateDto = new CreditValueCalculateDto();
		List<CreditValueCalculateDto.CreditValueCalculateBatch> batchIdList = new ArrayList<CreditValueCalculateDto.CreditValueCalculateBatch>();
		/* 保存执行上下文 */
		for (TCMmCreditDetailDTO creditDetail : creditDetailList) {
			CreditValueCalculateDto.CreditValueCalculateBatch cc = new CreditValueCalculateDto.CreditValueCalculateBatch();
			cc.setTransferId(creditDetail.getTransferId());
			cc.setCreidtId(creditDetail.getCreditCode());
			cc.setCreditDate(redeemDate);
			cc.setEachRepaymentValue(creditDetail.getThisRepaySum());
			batchIdList.add(cc);
		}
		creditValueCalculateDto.setBatchIdList(batchIdList);
		creditValueCalculateDto.setDealCode(busiNoForInteract);
		List<CreditValueCalculateResultDto> rslist = iCInteract.getCreditValue(creditValueCalculateDto);
		if (rslist == null) {
			return null;
		}
		Map<String, CreditValueCalculateResultDto> map = new HashMap<String, CreditValueCalculateResultDto>();
		for (CreditValueCalculateResultDto creditValueCalculateResultDto : rslist) {
			map.put(creditValueCalculateResultDto.getTransferId(), creditValueCalculateResultDto);
		}
		List<CreditDetailDto> resultlist = new ArrayList<CreditDetailDto>();
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			CreditValueCalculateResultDto creditValueCalculateResultDto = map.get(creditDetailDto.getTransferId());
			creditDetailDto.setThisMakeCreditorValue(creditValueCalculateResultDto.getCreditValue());
			resultlist.add(creditDetailDto);
		}

		return resultlist;
	}

	/**
	 * 债权赎回流水号
	 * 
	 * @param quotaCode
	 * @return
	 */
	public JResult doGetDealCode(StringBuffer dealCode) throws Exception {
		JResult result = new JResult();
		dealCode = dealCode.append(iCDeal.createDealCode(CimsConstant.BIZNO_TYPE_REDEMPTION));
		result.setSuccess(true);
		if (StringUtils.isBlank(dealCode))
			result.setSuccess(false);
		return result;
	}

	/**
	 * 选择赎回的债权明细，更新赎回状态，保存到债权明细表里
	 * 
	 * @param qcreditdto
	 * @param dealdto
	 */
	public void saveCreditDealDetail(RedemptionCreditDetailDto redemptionCreditDetailDto, TCMmCooperorgDealDTO dealdto) {
		redemptionCreditDetailDto.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_UNCK);// 交易占用
		// 更新额度债权明细状态
		creditRight.updateCreditDetailStatus(redemptionCreditDetailDto);
		// 保存债权交易明细
		creditRight.saveRedemptionCreditDealDetail(redemptionCreditDetailDto, dealdto);

	}

	/**
	 * 
	 * @Title removeDetailByCredit
	 * @Description 删除交易明细，更新债权明细状态
	 * @param baseDto
	 * @param transferIds
	 * @throws Exception
	 * @author lizhiqiang
	 * @date 2015-1-31-上午11:03:29
	 * @update
	 * @throws
	 */
	public void removeDetailByCredit(BaseDTO baseDto, String transferIds, String dealCode) throws Exception {
		RedemptionCreditDetailDto redemptionCreditDetailDto = new RedemptionCreditDetailDto();
		redemptionCreditDetailDto.setRedemptionStatus(null);// 交易占用
		redemptionCreditDetailDto.setTransferIds(transferIds);
		// 更新债权明细状态
		creditRight.updateCreditDetailStatus(redemptionCreditDetailDto);
		// 删除债权交易明细
		creditRight.deleteTCMmCreditDealDetailByTransferIds(baseDto, transferIds.replace(",", "','"), dealCode);
	}

	/**
	 * 删除交易信息，交易在途或者已完成不允许删除，先删除明细，再删除交易，如果明细对应的额度申请编号已经完成，则需要调用释放接口
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 *             String
	 * @author lizhiqiang
	 * @date 2015-1-29-下午4:49:42
	 * @update
	 * @throws
	 */
	public String doDeleteDeal(String ids) throws Exception {
		StringBuffer resultstr = new StringBuffer("交易流水号（");
		String[] id = ids.split(",");
		int count = 0;
		for (int i = 0; i < id.length; i++) {
			TCMmCooperorgDealDTO cooperorgDealDTO = cooperorgDealService.queryTCMmCooperorgDealByPrimaryKey(id[i]);
			if (!CimsConstant.DEAL_STATUS_FINISH.equals(cooperorgDealDTO.getCooperativeAgencyDealStatus())
					|| StringUtils.isEmpty(cooperorgDealDTO.getCooperativeAgencyDealStatus())) {
				// 删除明细
				Map<String, Object> searchParams = new HashMap<String, Object>();
				TCMmCreditDealDetailDTO creditDealDetailDTO = new TCMmCreditDealDetailDTO();
				creditDealDetailDTO.setDealStreamCode(cooperorgDealDTO.getDealCode());
				searchParams.put("dto", creditDealDetailDTO);
				List<TCMmCreditDealDetailDTO> creditDealDetailList = creditDealDetailService.searchTCMmCreditDealDetail(searchParams);
				if (creditDealDetailList.size() > 0) {
					//验证是否已经到了赎回日期
					TCMmCreditDealDetailDTO tCMmCreditDealDetailDTO = creditDealDetailList.get(0);
					if(DateTimeUtils.dateCompare(new Date(),tCMmCreditDealDetailDTO.getRedeemDate())){
						StringBuffer transferIds = new StringBuffer();
						for (TCMmCreditDealDetailDTO tcMmCreditDealDetailDTO : creditDealDetailList) {
							transferIds.append("," + tcMmCreditDealDetailDTO.getTransferId());
						}
						this.removeDetailByCredit(new BaseDTO(), transferIds.substring(1).toString(), cooperorgDealDTO.getDealCode());
					}
					
				}
				cooperorgDealService.deleteTCMmCooperorgDealByPrimaryKey(new BaseDTO(), id[i]);
			} else {
				count++;
				resultstr.append(cooperorgDealDTO.getDealCode() + ",");
			}
		}
		if ("交易流水号（".equals(resultstr.toString())) {

			resultstr = new StringBuffer("");
			resultstr.append("删除成功");
		} else {
			if (count > 0)
				resultstr.append("已经进入交易状态，不能删除，其余删除成功");
			else
				resultstr.append("已经进入交易状态，不能删除");
		}
		return resultstr.toString();
	}
	/**
	 * 发送结算请求
	 * @Title doSettleDeal
	 * @Description TODO 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-4-18-上午10:30:36
	 * @update 
	 * @throws
	 */
	public String settleDeal(String ids){
		String[] dealCodes = ids.split(",");
		StringBuffer result = new StringBuffer();
		for (String dealCode : dealCodes) {
			DealDto dealdto = new DealDto();
			dealdto.setDealCode(dealCode);
			dealdto.setCostState(CimsConstant.COST_STATUS_DJ);
			result.append(creditRight.doRedempSettleDeal(dealdto)).append("\n");
		}
		return result.toString();
	}
	/**
	 * 赎回导入处理：确认赎回的更改债权状态为赎回，调用赎回接口，取消的债权
	 * @Title doExcelImportResult
	 * @Description TODO
	 * @param creditDealList
	 * @throws Exception
	 * void
	 * @author lizhiqiang
	 * @date 2015-3-30-下午5:27:47
	 * @update
	 * @throws
	 */
	public void doExcelImportResult(List<CreditDetailDto> creditDealList, String dealCode) throws Exception {
		List<CreditDetailDto> resultcreditDealList = new ArrayList<CreditDetailDto>();
		Date dueDate = null;
		
		Date dealDate = null;
		if(StringUtils.isNotBlank(dealCode)){
			DealDto dealdto = new DealDto();
			dealdto.setDealCode(dealCode);
			List<TCMmCooperorgDealDTO>  dealdetolist = cooperorgDealService.searchTCMmCooperorgDeal(SearchParamUtil.getSearchParam(dealdto));
			if(dealdetolist!=null&&dealdetolist.size()>0){
				dealDate = dealdetolist.get(0).getRedemptionDate();
			}
		}
		
		for (CreditDetailDto creditDetailDto : creditDealList) {
			if(StringUtils.isEmpty(creditDetailDto.getDealCreditorStatus())||creditDetailDto.getDealThisMakeCreditorValue()==null||creditDetailDto.getRedeemDate()==null){
				throw new CimsException("交互状态、赎回债权价值、赎回日期必填！");
			}
			if (creditDetailDto.getDealCreditorStatus() != null && !"03".equals(creditDetailDto.getDealCreditorStatus())
					&& !("05").equals(creditDetailDto.getDealCreditorStatus())) {
				continue;
			}
			if (StringUtils.isEmpty(creditDetailDto.getTransferId())) {
				continue;
			}
			if (dueDate == null) {
				dueDate = creditDetailDto.getRedeemDate();
			}
			if(!creditDetailDto.getRedeemDate().equals(dealDate)){
				throw new Exception("债权明细的赎回日期与赎回交易的赎回日期不相等,请重新创建赎回交易！");
			}
			/*
			 * 1,更新债权明细表，更新赎回日期和赎回挑选状态（取消赎回的要改回去），把赎回价格也保存的一个单独字段里（MakeCreditorValue），
			 *   赎回价值保存到 thisMakeCreditValue
			 */
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCreditDetailDTO creditDetail = new TCMmCreditDetailDTO();
			TCMmCreditDealDetailDTO creditDealDetail = new TCMmCreditDealDetailDTO();
			creditDetail.setTransferId(creditDetailDto.getTransferId());
			searchParams.put("dto", creditDetail);
			creditDetail = creditDetailDao.searchTCMmCreditDetail(searchParams).get(0);
			
			//如果债权已经赎回  ，重复导入只更新结算状态、赎回价格、保证金
			if(CimsConstant.CREDIT_STATUS_RED.equals(creditDetail.getCreditorStatus())){
				
				TCMmCreditDealDetailDTO creditDealDetaildto = new TCMmCreditDealDetailDTO();
				creditDealDetaildto.setTransferId(creditDetailDto.getTransferId());
				creditDealDetaildto.setDealStreamCode(dealCode);
				Map<String, Object> searchParamsdeal = new HashMap<String, Object>();
				searchParamsdeal.clear();
				searchParamsdeal.put("dto", creditDealDetaildto);
				creditDealDetaildto = creditDealDetailDao.searchTCMmCreditDealDetail(searchParamsdeal).get(0);
				
				creditDealDetail.setTransferId(creditDetailDto.getTransferId());
				creditDealDetail.setDealStreamCode(dealCode);
				creditDealDetail.setMakeCreditorValue(creditDetailDto.getDealMakeCreditorValue());//赎回价格
				creditDealDetail.setCautionMoney(creditDetailDto.getCautionMoney());//保证金
				//待结算或者未结算 才更新状态
				if(CimsConstant.COST_STATUS_DJ.equals(creditDealDetaildto.getCostState())||CimsConstant.COST_STATUS_WJ.equals(creditDealDetaildto.getCostState())){
					creditDealDetail.setCostState(creditDetailDto.getCostState());//结算状态
				}
				searchParams.clear();
				searchParams.put("dto", creditDealDetail);
				dealDao.updateCreditDealDetail(searchParams);
				continue;
			}
			
			/*// 转让编号
			if (CimsConstant.CREDIT_STATUS_LOSE.equals(creditDetailDto.getDealCreditorStatus())) {
				creditDetail.setRedemptionStatus(null);
			} */
//			creditDetail.setMakeCreditorValue(creditDetailDto.getMakeCreditorValue());// 回复债权价值
			creditDetail.setRedeemDate(creditDetailDto.getRedeemDate());// 赎回日期
			searchParams.clear();
			searchParams.put("dto", creditDetail);
			creditDetailDao.updateTCMmCreditDetail(searchParams);// 更新交易明细表
			//2,更新债权交易明细表，保存回复的价格、赎回的状态、赎回日期
			creditDealDetail.setTransferId(creditDetailDto.getTransferId());
			creditDealDetail.setDealStreamCode(dealCode);
			creditDealDetail.setThisMakeCreditorValue(creditDetailDto.getDealThisMakeCreditorValue());//  赎回价值 5-13
			creditDealDetail.setMakeCreditorValue(creditDetailDto.getDealMakeCreditorValue());//赎回价格
			creditDealDetail.setCreditorStatus(creditDetailDto.getDealCreditorStatus());// 赎回状态
			creditDealDetail.setRedeemDate(creditDetailDto.getRedeemDate());// 赎回日期
			creditDealDetail.setCautionMoney(creditDetailDto.getCautionMoney());//保证金
			
			creditDealDetail.setCostState(creditDetailDto.getCostState());//结算状态
			searchParams.clear();
			searchParams.put("dto", creditDealDetail);
			
			//3,定期执行赎回
			if (CimsConstant.CREDIT_STATUS_RED.equals(creditDetailDto.getDealCreditorStatus())) {
				creditDetailDto.setThisCreditorValue(creditDetailDto.getDealThisMakeCreditorValue().setScale(2, BigDecimal.ROUND_HALF_UP));//切换字段，为了接口通用
				
				TCMmCreditDealDetailDTO creditDealDetaildto = new TCMmCreditDealDetailDTO();
				creditDealDetaildto.setTransferId(creditDetailDto.getTransferId());
				creditDealDetaildto.setDealStreamCode(dealCode);
				Map<String, Object> searchParamsdeal = new HashMap<String, Object>();
				searchParamsdeal.put("dto", creditDealDetaildto);
				creditDealDetaildto = creditDealDetailDao.searchTCMmCreditDealDetail(searchParamsdeal).get(0);
				if(creditDealDetaildto.getThisMakeCreditorValue().compareTo(creditDetailDto.getDealThisMakeCreditorValue())<0){
					throw new InteractException(java.text.MessageFormat.format(CimsExceptionConstant.REDEEM_OPERATION_FAIL, new Object[]{creditDetailDto.getCreditCode()}));
				}
				if(creditDealDetaildto.getThisMakeCreditorValue().compareTo(creditDetailDto.getDealThisMakeCreditorValue())==0){
					creditDetailDto.setIsWhole(CimsConstant.CREDIT_ISWHOLE);
					creditDetailDto.setThisRepaySumPercent(new BigDecimal(1));
				}else{
					creditDetailDto.setIsWhole(CimsConstant.CREDIT_NOWHOLE);
					//赎回比例
					creditDetailDto.setThisRepaySumPercent(creditDetailDto.getDealThisMakeCreditorValue().divide(creditDealDetaildto.getThisMakeCreditorValue(),6,BigDecimal.ROUND_HALF_UP));
				}
				//赎回债权价值为0的债权不调用接口
				if(creditDetailDto.getDealThisMakeCreditorValue().compareTo(new BigDecimal(0))>0)
				resultcreditDealList.add(creditDetailDto);
			}
			
			dealDao.updateCreditDealDetail(searchParams);
		}
		//更新流水统计信息
		dealDao.updateDealInfoForyDetailByDealCode(dealCode);
		
		if(resultcreditDealList.size() > 0){
			if (DateTimeUtils.dateCompare(dueDate, new Date())){
				abstractDueExecuteTaskManager.addDueExecuteTask("dueRedeemCreditDetail", dueDate,dealCode, resultcreditDealList);
			}else{
				doRedeemCreditDetail(creditDealList, dealCode);
			}
		}
		
	}
	
	/**
	 * @throws Exception 
	 * 处理直接导入赎回数据
	 * @Title doImprotCreatRedemption
	 * @Description TODO 
	 * void 
	 * @author lizhiqiang
	 * @date 2015-5-10-下午3:52:50
	 * @update 
	 * @throws
	 */
	public void doImprotCreatRedemption(DealDto dealDto,List<CreditDetailDto> creditDealList) throws Exception{
		//1，创建赎回交易流水
		StringBuffer dealCodesb = new StringBuffer();
     	this.doGetDealCode(dealCodesb);
     	String dealCode = dealCodesb.toString();
     	dealDto.setDealCode(dealCode);//交易流水号
     	dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);//新建
     	dealDto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_REDEEM);
     	dealDto.setDealDate(new Date());
     	Long dealId = cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
     	dealDto.setId(dealId);
     	
		
		//2， 更新额度债权明细状态
		
		/*Map<Object, Object> paramterMap = new HashMap<Object, Object>();
		paramterMap.put("dealDto", dealDto);
		batchService.batchInvoke(CCreditRightImpl.class, "updateCreditDetailStatusByCreditCode", creditDealList, paramterMap, 1000);
*/
//		creditRight.updateCreditDetailStatusByCreditCode(creditDealList,paramterMap);
		
		
		//3，插入债权交易明细
		creditRight.saveRedemptionCreditDealDetail(creditDealList, dealDto);
	}
	/**
	 * 调用赎回接口前更新本地债权的状态和当前债权价值,月还
	 * @Title updateTCMmCreditDetail
	 * @Description TODO
	 * @param creditDealList
	 * @return 
	 * List<CreditDetailDto> 
	 * @author lizhiqiang
	 * @date 2015-5-7-下午11:40:16
	 * @update 
	 * @throws
	 */
	public List<CreditDetailDto> updateTCMmCreditDetail(List<CreditDetailDto> creditDealList){
		
		List<CreditDetailDto> resultCreditDealList = new ArrayList<CreditDetailDto>();
		try {
		
		for (CreditDetailDto creditDetailDto : creditDealList) {
//		CreditValueChangedParam creditValueChangedParam = new CreditValueChangedParam();
		//1,更新债权明细表
		Map<String, Object> searchParams = new HashMap<String, Object>();
		TCMmCreditDetailDTO creditDetail = new TCMmCreditDetailDTO();
		creditDetail.setTransferId(creditDetailDto.getTransferId());
		searchParams.put("dto", creditDetail);
		creditDetail = creditDetailDao.searchTCMmCreditDetail(searchParams).get(0);
		// 转让编号
		if(CimsConstant.CREDIT_ISWHOLE.equals(creditDetailDto.getIsWhole())){
			creditDetail.setCreditorStatus(creditDetailDto.getDealCreditorStatus());// 回复状态
			creditDetail.setThisCreditorValue(new BigDecimal(0));
		}else{
			creditDetail.setRedemptionStatus(null);
			if(creditDetail.getThisCreditorValue().compareTo(new BigDecimal(0))>1){
			  creditDetail.setThisCreditorValue(creditDetail.getThisCreditorValue().subtract(creditDetailDto.getDealThisMakeCreditorValue()));// 剩余债权价值
			}
		}
		/*if(CimsConstant.CORE_CREDIT_STATUS_SETTLE_AHEAD.equals(creditDetail.getCoreCreditStatus())){
			if(creditDetailDto.getThisRepaySumPercent()!=null){
				creditDetail.setThisRepaySum(creditDetail.getThisRepaySum().subtract(creditDetail.getThisRepaySum().multiply(creditDetailDto.getThisRepaySumPercent()).setScale(2, BigDecimal.ROUND_HALF_UP)));
				//变更结算计划
				
				creditValueChangedParam.setCreditCode(creditDetail.getCreditCode());
				creditValueChangedParam.setTransferId(creditDetail.getTransferId());
				creditValueChangedParam.setRepaymentAmt(creditDetail.getThisRepaySum());
				Date billDate = SettleDateImpl.getNextSettleDateForBillDate(creditDetail.getBillDate());
				Map<String, Object> costPlanSearchParams = new HashMap<String, Object>();
				TCMmCostPlanDTO costPlanDto = new TCMmCostPlanDTO();
				costPlanDto.setCreditorCode(creditDetail.getCreditCode());
				costPlanDto.setTransferId(creditDetail.getTransferId());
				costPlanDto.setStartDate(billDate);
				costPlanSearchParams.put("dto", costPlanDto);
				List<TCMmCostPlanDTO>  cplist = costPlanDao.searchTCMmCostPlan(costPlanSearchParams);
				if(cplist!=null&&cplist.size()>0){
				costPlanDto = cplist.get(0);
				creditValueChangedParam.setTerm(costPlanDto.getCurrentTime().intValue());
				settlePlan.creditValueChanged(creditValueChangedParam);
				}else{
					logger.error(">>"+creditDetail.getTransferId() + "没有找到结算计划！");
				}
			}
		}*/
		searchParams.clear();
		searchParams.put("dto", creditDetail);
		resultCreditDealList.add(creditDetailDto);
		creditDetailDao.updateTCMmCreditDetail(searchParams);// 更新交易明细表
		}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return resultCreditDealList;
	}
	/**
     * @author zhiqiang
     * @description: 按条件查询结算计划列表
     * @date 2015-01-07 16:21:49
     * @param searchParams 条件
     * @return
     * @throws
     */
	public List<TCMmCostPlanDTO> searchTCMmCostPlan(Map<String,Object> searchParams) throws Exception {
	    List<TCMmCostPlanDTO> dataList = costPlanDao.searchTCMmCostPlan(searchParams);
        return dataList;
    }
	/**
	 * 调用赎回接口注册
	 * 注册同时更新债权的状态和当前债权价值，如果赎回价值等于当前债权价值把债权状态改成“已赎回”，如果不等于只更新债权价值（目的是当时能看见当前债权价值的变化）
	 * @Title doRegisterRedeemCreditDetail
	 * @Description TODO
	 * @param busiNoForInteract
	 * @param creditDealList
	 * void
	 * @author lizhiqiang
	 * @date 2015-3-30-下午3:55:03
	 * @update
	 * @throws
	 */
	public List<CreditDetailDto> doRegisterRedeemCreditDetail(String busiNoForInteract, List<CreditDetailDto> creditDealList) {
		List<CreditDetailDto> resultList = this.updateTCMmCreditDetail(creditDealList);
		iInteractAssist.registerDealIrtService(busiNoForInteract);
		/* 保存执行上下文 */
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "doRedeemCreditDetail", creditDealList,
				busiNoForInteract);
		return resultList;
	}

	/**
	 * 调用赎回接口
	 * 循环目的是为了把月还金额取出来
	 * @param creditDealList
	 * @param busiNoForInteract
	 * @throws Exception
	 */
	public void doRedeemCreditDetail(List<CreditDetailDto> creditDealList, String dealCode) {
		String cCode = "";
		List<DealDto>  deallist = dealService.getCooperorgDealByDealCodeStr(dealCode);
		if(deallist.size()>0){
			cCode = deallist.get(0).getCooperorgCode();
		}
		//1、本地更新
		List<CreditDetailDto> resultList = this.updateTCMmCreditDetail(creditDealList);
		//2、调用赎回接口
		RedeemParamDto redeemParamDto = new RedeemParamDto();
		redeemParamDto.setCreditDetailList(resultList);
		redeemParamDto.setDealCode(dealCode);
		redeemParamDto.setCCode(cCode);
		RedeemResultDto rrdto = iCInteract.redeemCreditRight(redeemParamDto);
		logger.info("赎回成功返回结果："+JSON.toJSONString(rrdto));
		if(rrdto!=null&&rrdto.getCreditList()!=null)
		this.updateCreditThisRepaySumByRedeem(rrdto.getCreditList());
		
		//3、更新流水状态
		TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
		cooperorgDealDTO.setDealCode(dealCode);
		cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);
		// 更新交易流水状态为在途
		try {
			dealService.updateDealStatusByDealCode(cooperorgDealDTO);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 赎回更新月还
	 * @Title updateCreditThisRepaySumByRedeem
	 * @Description TODO
	 * @param creditList 
	 * void 
	 * @author lizhiqiang
	 * @date 2015-5-28-上午11:15:12
	 * @update 
	 * @throws
	 */
	public void updateCreditThisRepaySumByRedeem(
			List<ResponseBackCreditValueDTO> creditList) {
		for (ResponseBackCreditValueDTO redto : creditList) {
			try {
			Map<String, Object> searchParams = new HashMap<String, Object>();
			TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
			dto.setTransferId(redto.getTransferId());
			dto.setThisRepaySum(redto.getDeliveryEachRepaymentValue());
			searchParams.put("dto", dto);
			dealDao.updateCreditThisRepaySumByRedeem(searchParams);
			
			
			//1,更新债权明细表
			Map<String, Object> creditDetailsearchParams = new HashMap<String, Object>();
			TCMmCreditDetailDTO creditDetail = new TCMmCreditDetailDTO();
			creditDetail.setTransferId(redto.getTransferId());
			creditDetailsearchParams.put("dto", creditDetail);
			List<TCMmCreditDetailDTO>  creditDetailList = creditDetailDao.searchTCMmCreditDetail(creditDetailsearchParams);
			if(creditDetailList==null||creditDetailList.size()==0){
				continue;
			}else{
				creditDetail = creditDetailList.get(0);
			}
			
			
			CreditValueChangedParam creditValueChangedParam = new CreditValueChangedParam();
			creditValueChangedParam.setCreditCode(creditDetail.getCreditCode());
			creditValueChangedParam.setTransferId(creditDetail.getTransferId());
			creditValueChangedParam.setRepaymentAmt(creditDetail.getThisRepaySum());
			Date billDate = SettleDateImpl.getNextSettleDateForBillDate(creditDetail.getBillDate());
			Map<String, Object> costPlanSearchParams = new HashMap<String, Object>();
			TCMmCostPlanDTO costPlanDto = new TCMmCostPlanDTO();
			costPlanDto.setCreditorCode(creditDetail.getCreditCode());
			costPlanDto.setTransferId(creditDetail.getTransferId());
			costPlanDto.setStartDate(billDate);
			costPlanSearchParams.put("dto", costPlanDto);
			List<TCMmCostPlanDTO> cplist = costPlanDao.searchTCMmCostPlan(costPlanSearchParams);
			if(cplist==null||cplist.size()==0){
				continue;
			}else{
				costPlanDto = cplist.get(0);
			}
			
			creditValueChangedParam.setTerm(costPlanDto.getCurrentTime().intValue());
			settlePlan.creditValueChanged(creditValueChangedParam);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @description 调用赎回接口注册
	 * @author shengzhoutao
	 * @param busiNoForInteract
	 *            流水号
	 * @param creditDetailList
	 *            债权明细的集合
	 */
	public void doRegisterRedeemCreditDetailForSettle(String busiNoForInteract, List<CreditDetailDto> creditDetailList) {
		iInteractAssist.registerDealIrtService(busiNoForInteract);
		/* 保存执行上下文 */
		interactClassInvokeService.saveInteractClassInvoke(busiNoForInteract, this.getClass(), "doRedeemCreditDetailForSettle", busiNoForInteract, creditDetailList);
	}

	/**
	 * @description 调用赎回接口
	 * @author shengzhoutao
	 * @param busiNoForInteract
	 *            流水号
	 * @param creditDetailList
	 *            债权明细的集合
	 */
	public void doRedeemCreditDetailForSettle(String busiNoForInteract, List<CreditDetailDto> creditDetailList) {
		List<CreditDetailDto> list = new ArrayList<CreditDetailDto>();
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			creditDetailDto.setIsWhole(CimsConstant.CREDIT_ISWHOLE);
			creditDetailDto.setRedeemDate(new java.util.Date());
			list.add(creditDetailDto);
		}
		RedeemParamDto redeemParamDto = new RedeemParamDto();
		redeemParamDto.setCreditDetailList(list);
		redeemParamDto.setDealCode(busiNoForInteract);
		iCInteract.redeemCreditRight(redeemParamDto);

		redeemParamDto = null;
		list = null;
	}

	/**
	 * @description 调用赎回接口
	 * @author shengzhoutao
	 * @param creditDetailList
	 *            债权明细的集合
	 */
	public void doRedeemCreditDetailForSettle(List<CreditDetailDto> creditDetailList) {
		// 接口注册
		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		doRegisterRedeemCreditDetailForSettle(busiNoForInteract, creditDetailList);

		// 调用接口
		doRedeemCreditDetailForSettle(busiNoForInteract, creditDetailList);
	}

	/**
	 * 赎回回滚
	 */
	public String doNoRedemptionDeal(String dealCode){
		try {
			Map<String, Object> paramMap  = new HashMap<String, Object>();
			paramMap.put("dealCode", dealCode);
			dealDao.doNoRedemptionDeal(paramMap);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	/**
	 * @throws Exception 
	 * 贷款明细全部赎回
	 * @Title doRedemmpCreditDetailByLoan
	 * @Description TODO
	 * @param loanlist 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-6-12-下午2:33:40
	 * @update 
	 * @throws
	 */
	public void doRedempCreditDetailByLoan(List<CreditDetailDto> loanlist , Date redeemDate) throws Exception{
		//1、本地保存
     	String dealCode = this.saveRedempDeal(loanlist , redeemDate);
     	
		//2、调用接口
		RedeemParamDto redeemParamDto = new RedeemParamDto();
		redeemParamDto.setFrontTransNo(iInteractAssist.getBusiNoForInteract());//前置流水号
		redeemParamDto.setDealCode(dealCode);//交易流水号
		
		List<TCMmCreditDetailDTO> tCMmCreditDetailDTOList = new ArrayList<TCMmCreditDetailDTO>();
		for (CreditDetailDto creditDetailDto : loanlist) {
			if(redeemParamDto.getCCode()==null||"".equals(redeemParamDto.getCCode())){
				redeemParamDto.setCCode(creditDetailDto.getCooperorgCode());
			}
			TCMmCreditDetailDTO tCMmCreditDetailDTO = new TCMmCreditDetailDTO();
			tCMmCreditDetailDTO.setCreditCode(creditDetailDto.getCreditCode());//合同编号
			tCMmCreditDetailDTO.setRedeemDate(redeemDate);//回购日期
			tCMmCreditDetailDTO.setThisRepaySum(creditDetailDto.getThisRepaySum());//月还
			tCMmCreditDetailDTO.setCoreCreditStatus(creditDetailDto.getCoreCreditStatus());//核心状态
			tCMmCreditDetailDTO.setProductType(creditDetailDto.getProductType());//合同类型
			tCMmCreditDetailDTOList.add(tCMmCreditDetailDTO);
		}
		redeemParamDto.settCMmCreditDetailDTOList(tCMmCreditDetailDTOList);
		iCInteract.sendLoanTransferBatchRedeemToCore(redeemParamDto);
	}
	
	/**
	 * 债权明细赎回
	 * @Title doRedempCreditDetailByCredit
	 * @Description TODO
	 * @param loanlist
	 * @param redeemDate
	 * @throws Exception 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-6-12-下午6:25:14
	 * @update 
	 * @throws
	 */
	public void doRedempCreditDetailByCredit(List<CreditDetailDto> creditlist , Date redeemDate) throws Exception{
		//1、本地保存
		String dealCode = this.saveRedempDeal(creditlist , redeemDate);
		
		CreditDetailDto cddto = creditlist.get(0);
		
		List<CreditDetailDto> tcreditlist = new ArrayList<CreditDetailDto>();
		for (CreditDetailDto creditDetailDto : creditlist) {
			creditDetailDto.setThisCreditorValue(creditDetailDto.getThisMakeCreditorValue());
			creditDetailDto.setIsWhole(CimsConstant.CREDIT_ISWHOLE);
			creditDetailDto.setRedeemDate(redeemDate);
			tcreditlist.add(creditDetailDto);
		}
		//2、调用接口
		RedeemParamDto redeemParamDto = new RedeemParamDto();
		redeemParamDto.setFrontTransNo(iInteractAssist.getBusiNoForInteract());
		redeemParamDto.setCreditDetailList(tcreditlist);
		redeemParamDto.setDealCode(dealCode);
		redeemParamDto.setCCode(cddto.getCooperorgCode());
		iCInteract.redeemCreditRight(redeemParamDto);
	}
	
	/**
	 * 受让明细赎回
	 * @Description TODO
	 * @param loanlist
	 * @param redeemDate
	 * @throws Exception 
	 * @update 
	 * @throws
	 */
	public void doTransfereeRedempDetailByCredit(List<CreditDetailDto> creditlist ,  Date redeemDate) throws Exception{
		//1、本地保存
		String dealCode = this.saveRedempDeal(creditlist , redeemDate);
		logger.info("=====受让明细赎回本地更新完毕========");
		//2、调用受让赎回接口
		CreditDetailDto cddto = creditlist.get(0);
		RedeemParamDto redeemParamDto = new RedeemParamDto();
		
		List<TCMmCreditDetailDTO> tCMmCreditDetailDTOList = new ArrayList<TCMmCreditDetailDTO>();
		for (CreditDetailDto creditDetailDto : creditlist) {
			TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
			dto.setTransferId(creditDetailDto.getTransferId());
			dto.setContractCode(creditDetailDto.getContractCode());
			dto.setRedeemDate(redeemDate);
			tCMmCreditDetailDTOList.add(dto);
		}
		redeemParamDto.settCMmCreditDetailDTOList(tCMmCreditDetailDTOList);
		redeemParamDto.setCCode(cddto.getCooperorgCode());
		redeemParamDto.setDealCode(dealCode);
		logger.info("=====受让明细赎调用核心4038========");
		iCInteract.sendSrCreditorBatchRedeemToCore(redeemParamDto);
		
	}
	
	/**
	 * @throws Exception 
	 * 创建赎回交易流水
	 * @Title saveRedempDeal
	 * @Description TODO
	 * @param dto 
	 * void 
	 * @author lizhiqiang
	 * @date 2016-6-12-下午3:59:09
	 * @update 
	 * @throws
	 */
	public String saveRedempDeal(List<CreditDetailDto> list , Date redeemDate) throws Exception{
		
		StringBuffer dealCodesb = new StringBuffer();
     	this.doGetDealCode(dealCodesb);
     	String dealCode = dealCodesb.toString();
     	
     	CreditDetailDto cddto = list.get(0);
		Date dealDate = new Date();
	    	// 创建交易流水信息
    	DealDto dealDto = new DealDto();
     	dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_FINISH);//完成赎回
     	if(CimsConstant.CREDIT_SOURCE_LOA.equals(cddto.getCreditSource())){
     		dealDto.setDealType(CimsConstant.DEAL_TYPE_LOAN_CREDIT_REDEEM);
     	}else if(CimsConstant.CREDIT_SOURCE_CRE.equals(cddto.getCreditSource())){
     		dealDto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_REDEEM);
     	}else{
     		dealDto.setDealType(CimsConstant.DEAL_TYPE_TRANSFER_CREDIT_REDEEM);
     	}
     	BigDecimal sumCreditorValue = BigDecimal.ZERO;
     	for (CreditDetailDto creditDetailDto : list) {
     		sumCreditorValue = sumCreditorValue.add(creditDetailDto.getThisMakeCreditorValue());
		}
     	
     	dealDto.setContractCode(cddto.getContractCode());
     	dealDto.setRedemptionDate(redeemDate);
     	dealDto.setDealDate(dealDate);//交易日期
     	dealDto.setCooperorgCode(cddto.getCooperorgCode());
     	dealDto.setAgreementCode(cddto.getAgreementCode());
     	dealDto.setDealCode(dealCode);
     	dealDto.setSumCreditorValue(sumCreditorValue);
     	dealDto.setDetialNumber(list.size());
     	cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
     	
     	for (CreditDetailDto creditDetailDto : list) {
     		TCMmCreditDealDetailDTO cdddto = new TCMmCreditDealDetailDTO();
			cdddto.setDealStreamCode(dealCode);// 交易编号
			cdddto.setTransferId(creditDetailDto.getTransferId());// 转让编号
			cdddto.setThisMakeCreditorValue(creditDetailDto.getThisMakeCreditorValue());//赎回债权价值
			cdddto.setCreditorStatus(CimsConstant.CREDIT_STATUS_RED);//赎回状态
			cdddto.setRedeemDate(redeemDate);//赎回日期
			Map<String, Object> cdddtoparamMap = new HashMap<String, Object>();
			cdddtoparamMap.put("dto", cdddto);
			// 保存债权交易流水明细表
			creditDealDetailDao.insertTCMmCreditDealDetail(cdddtoparamMap);
		}
     	Map<String, Object> upparamMap = new HashMap<String, Object>();
     	upparamMap.put("list", list);
     	upparamMap.put("creditorStatus", CimsConstant.CREDIT_STATUS_RED);
     	creditRedemptionDao.updateCreditDetailStatus(upparamMap);
    	return dealCode;
	}
}